package cn.edu.ecut.response;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;

@WebServlet( "/image/show/*" )
public class ImageShowServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request , HttpServletResponse response )
            throws ServletException, IOException {

        ServletContext application = request.getServletContext();

        String store = application.getInitParameter( "store" );

        String filename = "longge.png" ;
        
        Path source = Path.of( store , filename );

        // 设置 响应头 中的 content-type 字段的值
        // response.setHeader( "content-type" , "image/png" );
        response.setContentType( "image/png" );

        // 浏览器接受到 content-type 字段的值之后会采用image/png方式来处理后续接到的字节数据
        OutputStream out = response.getOutputStream() ;
        Files.copy( source , out );

    }

    @Override
    protected void doPost( HttpServletRequest request , HttpServletResponse response )
            throws ServletException, IOException {
        throw new RuntimeException( "获取数据应该使用GET请求而不是POST请求" );
    }

}
